const mysql = require('mysql')
const config = require('./../../config')
const dbConfig = config.database

const pool = mysql.createPool({
  host     :  dbConfig.HOST,
  user     :  dbConfig.USERNAME,
  password :  dbConfig.PASSWORD,
  database :  dbConfig.DATABASE
})

// 封装查询数据库语句 query
let query = function( sql, values ) {

  return new Promise(( resolve, reject ) => {
    pool.getConnection(function(err, connection) {
      if (err) {
        console.log( err )
        resolve( err )
      } else {
        connection.query(sql, values, ( err, rows) => {
          if ( err ) {
            console.log( err )
            reject( err )
          } else {
            resolve( rows )
          }
          connection.release()
        })
      }
    })
  })
}

// 查找管理员
let findAdminData = (username, password) => {
  let _sql = `select tid, username, avator, quote from admin_table where username="${username}" and password="${password}"`;
  return query(_sql);
}

// 文章
let getArticles = () => {
  let _sql = `select * from article_table where is_hot='0'`;
  return query(_sql);
}
let insertArticle = (title, summary, content, admin_tid) => {
  let _sql = `insert into article_table (title, summary, content, admin_tid) values ("${title}", "${summary}", "${content}", ${admin_tid})`;
  return query(_sql);
}
let getArticle = tid => {
  let _sql = `select * from article_table where tid=${tid}`;
  return query(_sql);
}
let deleteArticle = tid => {
  let _sql = `delete from article_table where tid=${tid}`;
  return query(_sql);
}
let updateArticle = (title, summary, content, admin_tid) => {
  let _sql = `update from article_table where tid=${tid}`;
  return query(_sql);
}
// 热门文章
let getHotArticles = () => {
  let _sql = `select * from article_table where is_hot='1' order by view desc, tid limit 10`
  return query(_sql);
}
module.exports = {
  query,
  findAdminData,
  // 文章
  insertArticle,
  deleteArticle,
  updateArticle,
  getArticles,
  getArticle,
  // 热门文章
  getHotArticles
}